<template>
    <el-form ref="form" :rules="rules" :model="loginForm" label-width="60px" class="login-card">
        <el-card shadow="always">
            <el-form-item class="login-btn" style="margin-left:80px">
                <el-image style="margin-left:100px;width: 200px; height: 100px"
                          src="https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg"
                          fit="fill"></el-image>
            </el-form-item>
            <el-form-item label="账号" prop="username">
                <el-input v-model="loginForm.username" prefix-icon="el-icon-user-solid"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password" autocomplete="off" prefix-icon="el-icon-s-goods"></el-input>
            </el-form-item>
            <el-container>
                <el-form-item prop="isChecked" class="login-btn">
                    <el-checkbox label="记住密码" v-model="loginForm.isChecked" name="type"></el-checkbox>
                </el-form-item>
                <el-form-item prop="idencode" class="login-btn">
                    <el-input v-model="loginForm.idencode" placeholder="验证码"></el-input>
                </el-form-item>
                <div class="code">
                    <span @click="createCode" class="codecontent" label="left">{{checkCode}}</span>
                </div>
            </el-container>
            <el-button-group class="login-btn">
                <el-button type="primary" @click="submitForm()">登录</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-button-group>
        </el-card>
    </el-form>
</template>

<script>
    // import http from 'axios'
    import {api_login} from '../api/login.js'

    export default {
        data() {
            return {
                loginForm: {
                    username: '',
                    password: '',
                    isChecked: false,
                    idencode: '',
                    fullscreenLoading: false,
                },
                checkCode: '',
                rules: {
                    username: [{
                        required: true,
                        message: '请输入账号',
                        trigger: 'blur'
                    },
                        {
                            min: 4,
                            max: 10,
                            message: '长度在 4 到 10 个字符',
                            trigger: 'blur'
                        }
                    ],
                    password: [{
                        required: true,
                        message: '请输入密码',
                        trigger: 'blur'
                    },
                        {
                            min: 4,
                            max: 10,
                            message: '长度在 4 到 10 个数字',
                            trigger: 'blur'
                        }
                    ]
                }

            }
        },
        mounted() {
            this.createCode();
        },
        methods: {
            submitForm() {
                var that = this;
                this.$refs.form.validate(async(valid) => {
                    //加载中 配置
                    const loading = this.$loading({
                        lock: true,
                        text: '加载中...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    // if (valid) {
                    //     //npm i vue-axios
                    //     //npm i axios
                    //     this.axios
                    //         .post('http://118.89.176.28:8080/admin/login', this.loginForm)
                    //         .then(result => {
                    //             console.log("result:::" + JSON.stringify(result.data.code));
                    //             console.log("idencode:::" + that.loginForm.idencode);
                    //             console.log("checkCode:::" + that.checkCode);
                    //             if (JSON.stringify(result.data.code) == 200 && that.loginForm.idencode == that.checkCode) {
                    //                 console.log("username:::" + this.loginForm.username)
                    //                 return this.$router.push({
                    //                     name: 'Main',
                    //                     params: {
                    //                         userId: '123'
                    //                     }
                    //                 })
                    //             }
                    //         })
                    //         .catch(function(err) {
                    //             console.log("err:::" + err);
                    //         });
                    // http.post('http://118.89.176.28:8080/admin/login', this.loginForm)
                    // .then(result => {
                    // 	console.log(result);
                    // })

                    // } else {
                    //     console.log('error submit!!');
                    //     return false;
                    // }
                    if (!valid) {
                        loading.close();
                        console.log("验证失败！");
                        return false;
                    }

                    //提交表单
                    const {data: res} = await api_login(this.loginForm.username, this.loginForm.password)
                    loading.close();
                    const result = res.data;
                    console.log("result.code:::"+JSON.stringify(res.code))
                    if (JSON.stringify(res.code) != 200) {
                        this.$message.error("用户名或密码错误！")
                        return false;
                    }

                    const token = result.tokenHead + result.token
                    //保存token到sessionStorge
                    console.log("token:::"+token)
                    window.sessionStorage.setItem('token', token)//会话结束后，会自动消除
                    //保存用户信息
                    //记住密码，保存到cookie，需要安装vue-cookie
                    if (this.loginForm.isChecked) {
                        this.$cookies.set('username', this.loginForm.username, '7D')
                        this.$cookies.set('password', this.loginForm.password, '7D')
                    } else {
                        this.$cookies.remove('username')
                        this.$cookies.remove('password')
                    }

                    console.log("result:::" + JSON.stringify(result.code));
                    console.log("idencode:::" + that.loginForm.idencode);
                    console.log("checkCode:::" + that.checkCode);
                    if (that.loginForm.idencode == that.checkCode) {
                        this.$message({
                            message: '登录成功！',
                            type: 'success'
                        });
                        console.log("username:::" + this.loginForm.username)
                        return this.$router.push({
                            name: 'Main',
                            params: {
                                userId: '123'
                            }
                        })
                    }else{
                        this.$message.error("验证码有误，注意大小写！")
                    }


                    // http.post('http://118.89.176.28:8080/admin/login', this.loginForm)
                    //     .then(result => {
                    //         console.log(result);
                    //     })


                });
            },
            resetForm() {
                this.$refs['form'].resetFields();
            },
            createCode() {
                let code = "";
                const codeLength = 4; //验证码的长度
                const random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                    'M', 'N', 'O', 'P', 'Q', 'R',
                    'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //随机数
                for (let i = 0; i < codeLength; i++) { //循环操作
                    let index = Math.floor(Math.random() * 36); //取得随机数的索引（0~35）
                    code += random[index]; //根据索引取得随机数加到code上
                }
                this.checkCode = code; //把code值赋给验证码
                console.log("createCode:::" + this.checkCode);
            },
        },
        created() {
            //在页面加载前，获取cookie值并绑定在值上
            this.loginForm.username = this.$cookies.get('username')
            this.loginForm.password = this.$cookies.get('password')
        }
    }
</script>

<style scoped>
    .login-card {
        width: 480px;
        margin: auto;
        transform: translateY(50%);
    }

    .login-btn {
        width: 100%;
    }

    .login-btn .el-button {
        width: 50%;
    }

    .login-btn .i {
        width: 50%;
    }

    .code {
        background-color: #DCDFE6;
        line-height: 1.7;
        margin-left: 10px;
        border-radius: 4px;
        border: 1px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        height: 40px;
        width: 100px;
    }

    .codecontent {
        color: #606266;
        font-size: 20px;
        margin: 10px;
    }
</style>
